package com.cabinet.utils;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.util.concurrent.RateLimiter;
//import com.things.common.utils.DateUtil;

import java.util.Date;
import java.util.concurrent.TimeUnit;

public class LimterUtil {



    static int num = 1;
    private static LoadingCache<String, RateLimiter> loadingCaches = CacheBuilder.newBuilder().refreshAfterWrite(5, TimeUnit.SECONDS)
            .build(new CacheLoader<String, RateLimiter>() {
                @Override
                public RateLimiter load(String key){
                    num++;
                    System.out.println("加载新的===="+num);
                    return RateLimiter.create(num);// 测试2个
                }
            });

    public static void runRateLimiter() {
        Long start = System.currentTimeMillis();

        for(int i = 1; i < 100; i ++ ) {
            RateLimiter limiter = loadingCaches.getUnchecked("test");
            // 请求RateLimiter, 超过permits(也就是create方法的参数，比如上面的10)会被阻塞，然后等待获取令牌
            limiter.acquire();
//            boolean result = limiter.tryAcquire();

//            if (!result) {
//                System.out.println("acquire未获得令牌:" + i );
//            } else {



//                System.out.println("acquire:"+ DateUtil.date3(new Date())+":" + i);
//            }
        }
        Long end = System.currentTimeMillis();
        System.out.println("限流后总耗时:" + (end - start));
    }


    public static void main(String[] args) {
        runRateLimiter();


        try {
            Thread.sleep(10000l);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        runRateLimiter();
    }

}
